import React, { useEffect, useState } from "react";
import {
  View,
  Text,
  Image,
  Camera
} from '@tarojs/components';
import {
  AtModal
} from 'taro-ui';
import {
	getStorageSync,
} from '@utils/util';
import {
  requestBaseUrl
} from '@config';
import {
  postUserArchivesAdd
} from '@/api';
import Taro, { useRouter } from '@tarojs/taro';
import photoMask from '@images/photoMask.png';
import overturnIcon from '@images/overturn.png';
import { useDispatch } from 'react-redux';
import {
  updateShowTemplates
} from '@stores/actions/user';
import './index.scss';

const CameraSection = () => {
  const dispatch = useDispatch();
  const [canSubmit, setCanSubmit] = useState(true);
  const router = useRouter();
  const [photo, setPhoto] = useState('');
  const [hasResult, setHasResult] = useState(false);
  const [isOpen, setIsOpen] = useState(false);
  const [error, setError] = useState('');
  const [top, setTop] = useState('0px');
  const [errorsList] = useState([
    {
      id: 0,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_side.png',
      name: '侧面'
    },
    {
      id: 1,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_occlusion.png',
      name: '有遮挡'
    },
    {
      id: 2,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_dark.png',
      name: '光线暗'
    },
    {
      id: 3,
      icon: 'https://jala-test-images.sndaurl.cn/images/example_vague.png',
      name: '模糊'
    }
  ]);
  const [positionType, setPositionType] = useState('front');

  useEffect(()=>{
    dispatch(updateShowTemplates(true));
    Taro.getSystemInfo({
      success: (res) => {
        let rate = res.safeArea.width / 750;
        let height = res.statusBarHeight;
        setTop(`${height}rpx`)
      }
    });
    let params = router.params;
    if (params.url) {
      setPhoto(params.url);
      setHasResult(true);
      dispatch(updateShowTemplates(false));
      if (params.isError == 1) {
        setIsOpen(true);
        const app = Taro.getApp();
        app.uploadStatus = false;
        setError(params.error);
        dispatch(updateShowTemplates(true));
      }
    }
  }, []);

  const takePhoto = () => {
    Taro.getSetting().then(res => {
      if (!res.authSetting['scope.camera']) {
        Taro.authorize({
          scope: 'scope.camera',
          success () {
            takePhotoNow();
          }
        }).catch(() => {
          Taro.showModal({
            content: '检测到您没打开摄像头权限，是否去设置打开？',
            confirmText: "确认",
            cancelText: "取消",
            confirmColor: '#FF3377',
            cancelColor: '#666666',
            success (res2) {
              //点击“确认”时打开设置页面
              if (res2.confirm) {
                Taro.openSetting({
                  success (res3) {
                    if (res3.authSetting['scope.camera']) {
                      takePhotoNow();
                    }
                  }
                })
              } else {
              }
            }
          })
        })
      } else {
        takePhotoNow();
      }
    });
  }

  const takePhotoNow = () => {
    const ctx = Taro.createCameraContext();
    ctx.takePhoto({
      quality: 'normal',
      success: (res) => {
        Taro.showLoading({
          title: '拍照中...',
        });
        Taro.uploadFile({
          url: `${requestBaseUrl}/v1/user/archives/upload`,
          filePath: res.tempImagePath,
          name: 'file',
          formData: {
            file: res.tempImagePath,
          },
          header: {
            'token': getStorageSync('token'),
            'user_type': 'douyin'
          },
          success: function (response) {
            let data = JSON.parse(response.data);
            setHasResult(true);
            if (data.error) {
              setError(data.error)
              setPhoto(res.tempImagePath);
              setIsOpen(true);
              dispatch(updateShowTemplates(true));
            } else {
              setPhoto(data.url);
              dispatch(updateShowTemplates(false));
            }
            Taro.hideLoading();
          },
          fail: function (res) {
          }
        });
      }
    })
  }

  const doReset = () => {
    setIsOpen(false);
    dispatch(updateShowTemplates(true));
    Taro.navigateBack({});
  }

  const onSubmit = () => {
    let params = {
      url: photo
    }
    if (canSubmit) {
      setCanSubmit(false);
      postUserArchivesAdd(params)
        .then(res=>{
          const app = Taro.getApp()
          app.needRelaodFaceprofile = true;
          setCanSubmit(true);
          Taro.navigateBack();
        })
        .catch(err => {
          setCanSubmit(true);
        })
    }
  }

  const onClose = () => {
    setIsOpen(false);
    const app = Taro.getApp();
    app.uploadStatus = false;
    dispatch(updateShowTemplates(true));
    Taro.navigateBack({});
  }

  const onChangeOverturn = () => {
    if (positionType == 'front') {
      setPositionType('back')
    } else {
      setPositionType('front')
    }
  }

  return (
    <View className="camera_view">
      {
        hasResult ? (
          <View className="camera">
            {
              isOpen ? (
                <View className="camera"></View>
              ) : (
                <Image
                  src={photo}
                  className="camera"
                  mode='aspectFill'
                />
              )
            }
          </View>
        ) : (
          <View>
            <Camera
              mode='normal'
              devicePosition={positionType}
              resolution='high'
              className="camera"
            />
            <Image
              src={photoMask}
              className="camera_view_modal"
              mode='aspectFill'
              style={{
                top: top
              }}
            />
          </View>
        )
      }
      {
        hasResult ? (
          <View className="camera_view_actions">
            <View className="camera_view_actions_item" onClick={()=>{doReset()}}>更换图片</View>
            <View className="camera_view_actions_item" onClick={()=>{onSubmit()}}>确定</View>
          </View>
        ) : (
          <View className="camera_view_action">
            {/* <View className="camera_view_action_cancel">取消</View> */}
            <View className="camera_view_action_photo" onClick={()=>{takePhoto()}}>
              <View className="camera_view_action_photo_center"></View>
            </View>
            <View className='camera_view_action_overturn' onClick={()=>{onChangeOverturn()}}>
              <Image
                src={overturnIcon}
                className='camera_view_action_overturn_icon'
              />
            </View>
          </View>
        )
      }
      <AtModal
        isOpened={isOpen}
      >
        <View className="tip_modal">
          <Image
            src='https://jala-test-images.sndaurl.cn/images/camera.png'
            className='tip_modal_tipImg'
          />
          <Image
            src='https://jala-test-images.sndaurl.cn/images/closeIcon.png'
            className='tip_modal_icon'
            onClick={()=>{onClose()}}
          />
          <View className="tip_modal_title">{error}</View>
          <View className="tip_modal_desc">再试试看，拍一张更清晰的照片吧</View>
          <View className="tip_modal_content">
            <Text className="tip_modal_content_label">拍摄指南</Text>
            帮助您获得更好的变妆效果
          </View>
          <View className="tip_modal_list">
            {
              errorsList.map(item=>
                <View className="tip_modal_list_item" key={item.id}>
                  <Image
                    src={item.icon}
                    className="tip_modal_list_item_img"
                    mode='aspectFill'
                  />
                  <View className="tip_modal_list_item_tip">
                    <Image
                      src='https://jala-test-images.sndaurl.cn/images/closeBg.png'
                      className="tip_modal_list_item_tip_icon"
                      mode='aspectFill'
                    />
                    {item.name}
                  </View>
                </View>
              )
            }
          </View>
          <View className="tip_modal_action" onClick={()=>{doReset()}}>重新上传</View>
        </View>
      </AtModal>
    </View>
  )
}
export default CameraSection;
